package cn.edu.swu.cly.miniwebsvr.core;

import cn.edu.swu.cly.miniwebsvr.handler.DefaultHandler;
import cn.edu.swu.cly.miniwebsvr.handler.EchoHandler;
import cn.edu.swu.cly.miniwebsvr.handler.TimeHandler;
import java.util.HashMap;
import java.util.Map;

public class Config {
    private final int port = 8080;
    private final String webRoot = "webroot";
    private final Map<String, Handler> handlerMap = new HashMap<>();

    private Config() {
        handlerMap.put("/", new DefaultHandler());          //服务器端的功能调用
        handlerMap.put("/time", new TimeHandler());
        handlerMap.put("/echo", new EchoHandler());
    }

    public static Config getInstance() {
        return Holder.INSTANCE;
    }

    private static class Holder {
        private static final Config INSTANCE = new Config();
    }

    public int getPort() {
        return port;
    }

    public String getWebRoot() {
        return webRoot;
    }

    public Handler getHandler(String url) {     //通过url地址，找到对应的处理对象处理用户输入的信息
        // TODO: 222024321072039/蔡礼洋 实现 URL 精确匹配或基础路径匹配逻辑

        //如果url是提取到相对路径，例如：/time
        Handler exactHandler = handlerMap.get(url);
        if (exactHandler != null) {         //不为空说明映射匹配完全一致
            return exactHandler;
        }

        //次级匹配
        if (url.contains(".")) {
            return handlerMap.get("/");
        }

        // 3. 处理根路径（/），通常对应index.html
        if (url.contains(".") && !url.equals("/")) {
            return handlerMap.get("/");
        }

        //都不匹配就默认处理
        return handlerMap.get("/");
    }
}
